//
//  ViewController.m
//  RTMKitDemo
//
//  Created by reyzhang on 2021/12/30.
//

#import "ViewController.h"
#import "RTMManager.h"
#import "UIViewController+HUD.h"
#import "UIViewController+Helper.h"
@interface ViewController () <YMRTMClientDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupForDismissKeyboard];
    [YMRTMManager updateDelegate:self];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
                                              initWithTitle:@"登出" style:UIBarButtonItemStylePlain target:self action:@selector(logout)];
    
}


- (void)logout {
    [[YMRTMManager client] logoutWithCompletion:^(YMRTMLogoutStatusCode code) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"login" object:nil];
    }];
}

- (IBAction)sendAction:(id)sender {
    
    if (self.peerTF.text.length == 0) {
        [self showHint:@"请输入Peer"];
        return;
    }
    
    if (self.messageTF.text.length == 0) {
        [self showHint:@"请输入要发送的消息"];
        return;
    }
    
    YMRTMMessage *message = [YMRTMMessage createPeerMessageWithPeerId:self.peerTF.text
                                                             data:self.messageTF.text];
    
    [[YMRTMManager client] sendMessage:message toPeer:self.peerTF.text completion:^(YMRTMSendPeerMessageStatusCode code) {
        self.showLabel.text = [NSString stringWithFormat:@"发送消息给%@: %@",self.peerTF.text, self.messageTF.text];
    }];
    
}


#pragma mark - RTMClientDelegate

- (void)rtmClient:(YMRTMClient *)client didReceiveMessage:(YMRTMMessage *)message {
    self.showLabel.text = [NSString stringWithFormat:@"收到来自%@的消息：%@",message.tid, message.data];
}


- (void)rtmClient:(YMRTMClient *)client connectionStateChanged:(YMRTMConnectionState)state {
    switch (state) {
        case RTMConnectionStateConnected:
            [self showHint:@"连接成功"];
            break;
        case RTMConnectionStateAborted:
            [self showHint:@"同一账号在另外设备上登录,您被迫下线"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"login" object:nil];
            break;
        case RTMConnectionStateConnecting:
            [self showHint:@"正在连接"];
            break;
        case RTMConnectionStateReConnecting:
            [self showHint:@"正在重连"];
            break;
        default:
            break;
    }
}
@end
